import { defineComponent } from 'vue'
import { ElMenu, ElSubMenu, ElMenuItem } from 'element-plus'

export default defineComponent({
  name: 'BaseMenu',
  props: {
    menus: {
      type: Array,
      default: () => []
    },
    ...ElMenu.props
  },
  emits: ['menuItemClick'],
  setup(props, { emit }) {
    const onMenuItemClick = (path, item) => {
      emit('menuItemClick', path, item)
    }
    const renderMenuItems = (menus, parentIndex) => {
      if (!menus?.length) {
        return null
      }
      return menus.map((item, index) => {
        const { children, meta, path } = item
        const realIndex = parentIndex
          ? `${parentIndex}-${index}`
          : String(index)
        if (!children?.length) {
          return (
            <ElMenuItem
              v-slots={{
                title: () => meta.title,
                default: () => <i class={meta.icon}></i>
              }}
              onClick={() => onMenuItemClick(path, item)}
              index={realIndex}
            ></ElMenuItem>
          )
        }
        const subMenuSlots = {
          title: () => (
            <>
              <i class={meta.icon}></i>
              <span>{meta.title}</span>
            </>
          )
        }
        return (
          <ElSubMenu index={realIndex} v-slots={subMenuSlots}>
            {renderMenuItems(children, index)}
          </ElSubMenu>
        )
      })
    }
    return () => <ElMenu {...props}>{renderMenuItems(props.menus)}</ElMenu>
  }
})
